package struct;

import java.util.Collection;

/**
 * Created by qq65827 on 2015/1/31.
 */
public class LinkedList<E> {

    int size;

    Node<E> first;

    Node<E> last;

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public Node<E> getLast() {
        return last;
    }

    public void setLast(Node<E> last) {
        this.last = last;
    }

    public LinkedList() {
    }

    public LinkedList(Collection<E> c) {
        this();
        //这段先不写
    }

    //先做成单链表

    private static class Node<E>{
        E e;

        public E getE() {
            return e;
        }

        public void setE(E e) {
            this.e = e;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }

        Node<E> next;
        //Node<E> prev;

        Node() {
        }

        Node(Node<E> next, E e) {
            this.e = e;
            this.next = next;
        }
    }

    public void add(int index,E e) {
        checkIsExist(index);
        Node<E> newnode = new Node<>(null,e);
        if (first == null
                ) {
            this.first = newnode;
            this.last = newnode;
            size++;
        } else {
            last.next = newnode;
            last = newnode;
            size++;
        }
    }

    public E get(int index) {
        checkIsExist(index);
        return node(index).e;
    }

    public Node<E> node(int index) {
        Node<E> x = first;
        for (int i = 0; i < (size-1); i++) {
            x = x.next;
        }
        return x;
    }

    public void checkIsExist(int index) {
        if (size == 0 && index == 0) {
            return ;
        }
        if (this.size < index) {
            if (!isPositionIndex(index)) {
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
            }
        }
    }

    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }






}
